﻿using KYJBLL;
using KYJScadaProModbusRtu;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using thinger.ControlLib;

namespace KYJScadaProModbusRTU
{
    public partial class FrmParamSet : Form
    {
        public FrmParamSet()
        {
            InitializeComponent();

            //开启定时器
            updateTimer = new Timer();
            updateTimer.Interval = 200;
            updateTimer.Tick += UpdateTimer_Tick;
            updateTimer.Start();
            //FormClosing事件关闭定时器
            this.FormClosing += (sender, e) =>
            {
                this.updateTimer.Stop();
            };

            //根据配置更新控件状态
            this.tog_AutoStart.IsChecked = CommomMethods.sysConfig.AutoStart;
            this.tog_AutoLogin.IsChecked = CommomMethods.sysConfig.AutoLogin;
            this.tog_AutoLock.IsChecked = CommomMethods.sysConfig.AutoLock;

            this.up_LockPeriod.CurrentValue = CommomMethods.sysConfig.LockPeriod;
            this.up_ShowSeriesCount.CurrentValue = CommomMethods.sysConfig.ShowSeriesCount;

            this.up_LockPeriod.ValueChanged += new System.EventHandler(this.up_LockPeriod_ValueChanged);

            this.up_ShowSeriesCount.ValueChanged += new System.EventHandler(this.up_ShowSeriesCount_ValueChanged);//剪切来的
        }

        //实时更新的定时器
        private Timer updateTimer;

        private SQLiteManage sQLiteManage = new SQLiteManage();

        private void UpdateTimer_Tick(object sender, EventArgs e)
        {
            UpdateCommon(this.panelEnhanced1);
        }
        private void UpdateCommon(Control parentControl)
        {
            if (CommomMethods.plcDevice != null && CommomMethods.connectState)//设备连接状态
            {
                foreach (Control item in parentControl.Controls)
                {
                    //更新TextSet显示
                    if (item is TextSet textSet)
                    {
                        if (textSet.BindVarName?.Length > 0)
                        {
                            float value = 0.0f;
                            if (float.TryParse(CommomMethods.plcDevice[textSet.BindVarName]?.ToString(), out value))
                            {
                                textSet.CurrentValue = value.ToString("f1");
                            }
                        }
                    }
                    else if (item.HasChildren)//递归
                    {
                        UpdateCommon(item);
                    }
                }
            }
        }

        private void textSetCommon_ControlDoubleClick(object sender, EventArgs e)
        {
            if (sender is TextSet textSet)
            {
                if (textSet.BindVarName != null && textSet.BindVarName.Length > 0)
                {
                    FrmModify frmModify = new FrmModify(textSet.TitleName, textSet.BindVarName, textSet.CurrentValue);
                    frmModify.ShowDialog();
                }
            }
        }

        #region 系统相关配置
        private void tog_AutoLogin_CheckedChanged(object sender, EventArgs e)
        {
            if(CommomMethods.SaveAutoLogin(((Toggle)sender).IsChecked))
            {
                CommomMethods.AddOPLog(false, "修改软件自动登录方式:" + ((Toggle)sender).IsChecked.ToString());
                CommomMethods.GetSysConfig();
            }
        }

        private void tog_AutoStart_CheckedChanged(object sender, EventArgs e)
        {
            if (CommomMethods.SaveAutoStart(((Toggle)sender).IsChecked))
            {
                //写入注册表
                AutoStart(((Toggle)sender).IsChecked);

                CommomMethods.AddOPLog(false, "修改开机自动启动方式:" + ((Toggle)sender).IsChecked.ToString());
                CommomMethods.GetSysConfig();
            }
        }

        #region 修改程序在注册表的键值
        private void AutoStart(bool isAuto = true)
        {
            if (isAuto == true)
            {
                RegistryKey R_local = Registry.CurrentUser;
                RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\windows\CurrentVersion\Run");
                R_run.SetValue("KYJPro", System.Windows.Forms.Application.ExecutablePath);
                R_run.Close();
                R_local.Close();
            }
            else
            {
                RegistryKey R_local = Registry.CurrentUser;
                RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\windows\CurrentVersion\Run");
                R_run.DeleteSubKey("KYJPro", false);
                R_run.Close();
                R_local.Close();
            }
        }
        #endregion

        private void tog_AutoLock_CheckedChanged(object sender, EventArgs e)
        {
            if (CommomMethods.SaveAutoLock(((Toggle)sender).IsChecked))
            {
                CommomMethods.AddOPLog(false, "修改无操作自动锁屏方式：" + ((Toggle)sender).IsChecked.ToString());
                CommomMethods.GetSysConfig();
            }
        }

        private void up_LockPeriod_ValueChanged(object sender, EventArgs e)
        {
            if (CommomMethods.SaveLockPeriod(Convert.ToInt32(((UpDownLabel)sender).CurrentValue)))
            {
                CommomMethods.AddOPLog(false, "修改锁屏间隔时间：" + ((UpDownLabel)sender).CurrentValue.ToString());
                CommomMethods.GetSysConfig();
            }
        }

        private void up_ShowSeriesCount_ValueChanged(object sender, EventArgs e)
        {
            if (CommomMethods.SaveShowSeriesCount(Convert.ToInt32(((UpDownLabel)sender).CurrentValue)))
            {
                CommomMethods.AddOPLog(false, "修改曲线显示数量：" + ((UpDownLabel)sender).CurrentValue.ToString());
                CommomMethods.GetSysConfig();
            }
        }
        #endregion

        private void btn_CreateTable_Click(object sender, EventArgs e)
        {
            if (new FrmMessageBoxWithAck("是否确定要重新生成数据表？", "重新生成").ShowDialog() == DialogResult.OK)
            {
                List<string> columns = new List<string>() { "InsertTime" };
                columns.AddRange(CommomMethods.plcDevice.StoreVarList.Select(c => c.VarName).ToList());
                var result = sQLiteManage.ReCreateActualTable("ActualData", columns);
                if (result.IsSuccess)
                {
                    CommomMethods.AddLog(false, "重新生成实时数据表：成功");

                    new FrmMessageBoxWithoutAck("重新生成实时数据表成功","重新生成").ShowDialog();
                }
                else
                {
                    CommomMethods.AddLog(false, "重新生成实时数据表：失败");

                    new FrmMessageBoxWithoutAck("重新生成实时数据表失败" + result.Message, "重新生成").ShowDialog();
                }
            }
        }

        #region 减少闪烁
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams parss = base.CreateParams;
                parss.ExStyle |= 0x02000000;
                return parss;
            }
        }
        #endregion
    }
}
